package vm

import (
	"context"
	"flag"
	"fmt"
	"github.com/2spmohanty/gosphere/operation"
	"github.com/vmware/govmomi/view"
	"github.com/vmware/govmomi/vim25/mo"
)

func VMClone() {
	vc := flag.String("vc", "192.168.93.151", "Enter vCenter IP/ FQDN")
	user := flag.String("user", "root", "vCenter User")
	pass := flag.String("pass", "", "Enter vCenter pass")
	flag.Parse()

	fmt.Printf("pass=%s\n", *pass)
	vcenter := operation.NewVCenter(*vc, *user, *pass)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	err := vcenter.Connect(ctx)
	if err != nil {
		fmt.Printf("Failed to connect to vCenter: %s\n", err)
		return
	}

	fmt.Printf("Connected to vCenter: %s\n", *vc)

	// Create view of VirtualMachine objects
	c := vcenter.Client.Client
	m := view.NewManager(c)

	v, err := m.CreateContainerView(ctx, c.ServiceContent.RootFolder, []string{"VirtualMachine"}, true)
	if err != nil {
		fmt.Printf("Failed to connect to vCenter: %s\n", err)
		return
	}

	defer v.Destroy(ctx)

	// Retrieve summary property for all machines
	// Reference: http://pubs.vmware.com/vsphere-60/topic/com.vmware.wssdk.apiref.doc/vim.VirtualMachine.html
	var vms []mo.VirtualMachine
	err = v.Retrieve(ctx, []string{"VirtualMachine"}, []string{"summary"}, &vms)
	if err != nil {
		fmt.Printf("Failed to connect to vCenter: %s\n", err)
		return
	}

	// Print summary per vm (see also: govc/vm/info.go)

	for _, vm := range vms {
		fmt.Printf("虚拟机：%s: %s\n", vm.Summary.Config.Name, vm.Summary.Config.GuestFullName)

	}

	fmt.Println("Starting Clone ....")

	// vmops := operation.VMOperation{Context: ctx, Vcenter: vcenter}

	//vmMor, rs := vmops.CloneVM("Test-VM-Last", true, &hst, vm, &clst, datacenter, &dst)

	/*var vmt mo.VirtualMachine
	err = pc.RetrieveOne(ctx, vmMor.Reference(), nil, &vmt)
	fmt.Println("The New VM is ", vmt.Name)
	fmt.Println("The state of cloning is ", rs)*/

}
